<?php
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;





/**
 * @name  数组打印
 */
function p($data){
    // 定义样式
    $str='<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 13px;line-height: 1.42857;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
    // 如果是boolean或者null直接显示文字；否则print
    if (is_bool($data)) {
        $show_data=$data ? 'true' : 'false';
    }elseif (is_null($data)) {
        $show_data='null';
    }else{
        $show_data=print_r($data,true);
    }
    $str.=$show_data;
    $str.='</pre>';
    echo $str;
	exit;
}
/**
 * @name  获取当前域名
 */
function getHttpType()
{
    $http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    return $http.$_SERVER['HTTP_HOST'];
}
/**
 * @name  将百度编辑器的content的图片转换为绝对路径
 */
function replacePicUrl($content = null){
    $con =getHttpType();
    if ($con){
        //提取图片路径的src的正则表达式 并把结果存入$matches中
        preg_match_all("/<img(.*)src=\"([^\"]+)\"[^>]+>/isU",$content,$matches);
        $img = "";
        if(!empty($matches)) {
            //注意，上面的正则表达式说明src的值是放在数组的第三个中
            $img = $matches[2];
        }else {
            $img = "";
        }
        if (!empty($img)) {
            $patterns= array();
            $replacements = array();
            foreach($img as $imgItem){
                $final_imgUrl = $con.$imgItem;
                $replacements[] = $final_imgUrl;
                $img_new = "/".preg_replace("/\//i","\/",$imgItem)."/";
                $patterns[] = $img_new;
            }

            //让数组按照key来排序
            ksort($patterns);
            ksort($replacements);

            //替换内容
            $vote_content = preg_replace($patterns, $replacements, $content);

            return $vote_content;
        }
    } 
    return $content;
}
/**
 * @name  获取当前lavarel版本
 */
function laravel_version(){
    $laravel = app();
    return $laravel::VERSION;
}

/**
 * @name  获取服务器上传上线
 */
function get_config_var(){
    return get_cfg_var("upload_max_filesize")?get_cfg_var("upload_max_filesize"):"不允许上传";
}

/**
 * @name  时间重组
 * @param time 时间
 * @return 返回重组时间格式
 */  
function time_data($time){
	$n = 0;
	for($i = 1;$i <= 3;$i++) {
		$n = strpos($time,'-',$n);
		$i != 3 && $n++;
	}
	$kaddtime=trim(substr($time,0,$n));
	$xaddtime=trim(substr($time,$n+1));
	return [$kaddtime,$xaddtime];
}

/**
 * @name  查询条件
 * @param model 模型
 * @param params 所有参数
 * @return 返回模型
 */
function query_condition($model,$params,$key="username"){
	if (!empty($params['created_at'])){
		$model = $model->whereBetween('created_at',time_data($params['created_at']));
	}
	if (!empty($params['updated_at'])){
		$model = $model->whereBetween('updated_at',time_data($params['updated_at']));
	}
	if (!empty($params['key'])){
		$key_arr = explode('|',$key);
		foreach($key_arr as $k=>$v){
			if($k){
				$model = $model->orWhere($v,'like','%' . $params['key'] . '%');
			}else{
				$model = $model->where($v,'like','%' . $params['key'] . '%');
			}
		}
	}                  
	if (isset($params['status']) && $params['status'] != ''){
		$model = $model->where('status',$params['status']);
	}
	return $model;
}

/**
 * @name  删除文件夹下的所有文件
 */  
function deldir($dir){
	$dh=opendir($dir);
	while ($file=readdir($dh)) {
		if($file != "." && $file != "..") {
		  $fullpath=$dir."/".$file;
		  if(!is_dir($fullpath)) {
			  unlink($fullpath);
		  }
		}
	}
}

/**
 * @name  邮件发送
 * @param data Array
 * @return 成功返回true 失败返回false
 */
function email($data){
	//$data['content'] = replacePicUrl($data['content']);
	Mail::send('admin::layouts.email',['data'=>$data],function($message)use($data){
		$message->from(config('mail.username'),config('mail.name'));
		$message ->to($data['email'])->subject($data['title']);
	});
	if(empty(Mail::failures())){
		return true;
	}else{
		return false;
	}
}	
 
/**
 * @name  百度seo推送
 */	
function baidu_t($baidu_url,$baidu_key,$urls){
	$api = "http://data.zz.baidu.com/urls?site=".$baidu_url."&token=".$baidu_key;
	$ch = curl_init();
	$options =  array(
		CURLOPT_URL => $api,
		CURLOPT_POST => true,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_POSTFIELDS => implode("\n", $urls),
		CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
	);
	curl_setopt_array($ch, $options); 
	$result = curl_exec($ch);
	$result = json_decode($result,true);
	return $result['remain'];    
	if(isset($result['remain'])){
		return true;
	}else{
		return false;
	}
}		



/**
 * @name 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function juheCurl($url, $params = false, $ispost = 0)
{
    $httpInfo = array();
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {  
            curl_setopt($ch, CURLOPT_URL, $url.'?'.http_build_query($params));
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
} 
/**
 * @name  获取目录下的所有文件夹
 */	
function get_dir($dir) {
	$dirArray[]=NULL;
	if (false != ($handle = opendir ( $dir ))) {
		$i=0;
		while ( false !== ($file = readdir ( $handle )) ) {
			//去掉"“.”、“..”以及带“.xxx”后缀的文件
			if ($file != "." && $file != ".."&&!strpos($file,".")) {
				$dirArray[$i]=$file;
				$i++;
			}
		}
		//关闭句柄
		closedir ( $handle );
	}
	return $dirArray;
}
/**
 * @name  PHP格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}



/**
 * @name  错误提示
 * @param  msg   错误提示语
 * @param  url   跳转路径
 */
function s_error($msg,$url){
$str  = <<<STR
	<!DOCTYPE html>
	<html>
	<head>
		<meta charset="utf-8">
		<title>"$msg"</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="format-detection" content="telephone=no">
		<link rel="stylesheet" href="/admins/plugins/layui/css/layui.css" media="all" />
		<link rel="stylesheet" href="/admins/css/global.css" media="all">
	</head>
	<body>
		<div class="system-message">
		</div>
		<script type="text/javascript" src="/admins/plugins/layui/layui.js"></script>
		<script type="text/javascript">
			layui.use('layer', function() {
				var layer = layui.layer;
				layer.msg("$msg", {time: 2000,icon:2},function(){
					location.href = "$url";
				});
			});
		</script>
	</body>
	</html>
STR;
	echo $str;exit();
}
/**
 * @name  成功提示
 * @param  msg   成功提示语
 * @param  url   跳转路径
 */
function s_success($msg,$url){
$str  = <<<STR
	<!DOCTYPE html>
	<html>
	<head>
		<meta charset="utf-8">
		<title>"$msg"</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="format-detection" content="telephone=no">
		<link rel="stylesheet" href="/admins/plugins/layui/css/layui.css" media="all" />
		<link rel="stylesheet" href="/admins/css/global.css" media="all">
	</head>
	<body>
		<div class="system-message">
		</div>
		<script type="text/javascript" src="/admins/plugins/layui/layui.js"></script>
		<script type="text/javascript">
			layui.use('layer', function() {
				var layer = layui.layer;
				layer.msg("$msg", {time: 2000,icon:1},function(){
					location.href = "$url";
				});
			});
		</script>
	</body>
	</html>
STR;
	echo $str;exit();
}

/**
 * @name  获取mysql版本
 */
function mysql_v(){
    $version = DB::select("select version()");
	return json_decode(json_encode($version), true)[0]['version()'];
}
/**
 * @name  一维数组json_encode中文乱码
 */
function s_json_encode($data){
	foreach($data as $key => $value){  
		$data[$key] = urlencode($value);  
	}
	return urldecode(json_encode($data));
} 
/**
 * @name  二维数组json_encode中文乱码
 */
function s_json_encodes($data){
	$count = count($data);
	for($k=0;$k<$count;$k++){
		foreach($data[$k] as $key => $value){  
			$data[$k][$key] = urlencode($value);  
		}
	}
	return urldecode(json_encode($data));
} 
/**
 * @name  对象转数据
 */
function obj_to_arr($object){
	return json_decode(json_encode($object), true);
}
/**
 * @name  生成二维码
 * @param text 用来生成二维码的内容（一般使用网址）
 * @param size 尺寸大小
 * @param color 颜色
 * @param backgroundColor 背景颜色
 * @param margin 外边距
 * @param logo_url logo路径
 * @param code_url 生成二维码路径
 */
function get_code($data = []){
	if(!isset($data['size'])){
		$data['size'] = 200;
	}
	if(!isset($data['color'])){
		$data['color'] = [0,0,0];
	}
	if(!isset($data['backgroundColor'])){
		$data['backgroundColor'] = [255,255,255];
	}
	if(!isset($data['margin'])){
		$data['margin'] = 0;
	}
	if(isset($data['code_url'])){
		$or_code = QrCode::format('png')->size($data['size']);
	}else{
		$or_code = QrCode::size($data['size']);
	}			
	$or_code = $or_code->errorCorrection('H')
				->encoding('UTF-8')
				->margin($data['margin'])
				->color($data['color'][0],$data['color'][1],$data['color'][2])
				->backgroundColor($data['backgroundColor'][0],$data['backgroundColor'][1],$data['backgroundColor'][2]);
	if(isset($data['logo_url'])){
		$or_code = $or_code->merge(public_path($data['logo_url']),.3,true);
	}
	if(isset($data['code_url'])){
		$or_code = $or_code->generate($data['text'],public_path($data['code_url']));
	}else{
		$or_code = $or_code->generate($data['text']);
	}
	return $or_code;  
} 
/**
 * 基于PHP的 mb_substr，iconv_substr 这两个扩展来截取字符串，中文字符都是按1个字符长度计算；
 * 该函数仅适用于utf-8编码的中文字符串。
 *
 * @param  $str      原始字符串
 * @param  $length   截取的字符数
 * @param  $append   替换截掉部分的结尾字符串
 * @return 返回截取后的字符串
 */
function sub_str($str, $length = 0, $append = '***') {
    $str = trim($str);
    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength) {
        return $str;
    } elseif ($length < 0) {
        $length = $strlength + $length;
        if ($length < 0) {
            $length = $strlength;
        }
    }

    if ( function_exists('mb_substr') ) {
        $newstr = mb_substr($str, 0, $length, 'utf-8');
    } elseif ( function_exists('iconv_substr') ) {
        $newstr = iconv_substr($str, 0, $length, 'utf-8');
    } else {
        //$newstr = trim_right(substr($str, 0, $length));
        $newstr = substr($str, 0, $length);
    }

    if ($append && $str != $newstr) {
        $newstr .= $append;
    }

    return $newstr;
}
/**
 * @name  生成订单号
 */
function make_order_no()
{
	$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
	$orderSn =
		$yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date(
			'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
			'%02d', rand(0, 99));
	return $orderSn;
}
